package org.example;

import java.util.*;

/**
 * 游戏本体
 *
 * @author tght
 */
public class Game {

    /**
     * 洗好的牌
     */
    private PokeBean[] gamePokeArray;

    /**
     * 本场游戏所有的参与者
     */
    private List<Player> players = new ArrayList<>();

    public void start() {
        // 0、玩家准备
        addGamePlayer();
        // 1.欢迎
        welcome();
        // 2.初始化
        initialize();
        // 3.循环让每位平民操作
        loopPlayerDoAction();
        // 4.庄家要牌
        dealerTakesTheCards();
        // 5.展示双方的点数判断胜负
        gameOver();
    }

    private void dealerTakesTheCards() {
        for (Player player : this.players) {
            if (player.getRole().equals(RoleEnum.CROUPIER)) {
                // 翻开暗牌
                player.getPokeBeans().forEach(poke -> {
                    if (!poke.getShow()) {
                        poke.setShow(true);
                    }
                });
                GameUtil.showPlayerPoke(player);
                // 是否拿牌
                int maxScore = GameUtil.getMaxScore(player);
                while (true) {
                    if (maxScore <= 16) {
                        //  拿牌
                        PokeBean pokeBean = GameUtil.dealCards(gamePokeArray);
                        player.addPoke(pokeBean);
                        maxScore = player.getMaxScore();
                    } else {
                        // 停止拿牌
                        break;
                    }
                }
            }
        }
    }


    private void loopPlayerDoAction() {
        for (Player player : this.players) {
            if (player.getRole().equals(RoleEnum.CROUPIER) || player.getGameJoinStatus().equals(GameJoinEnum.REVEAL_CARDS)) {
                continue;
            }
            System.out.printf("%s 您是否需要牌？y/n%n",player.getName());
            Scanner sc = new Scanner(System.in);
            while (true) {
                String next = sc.next();
                if ("y".equalsIgnoreCase(next)) {
                    // 要牌
                    PokeBean pokeBean = GameUtil.dealCards(gamePokeArray);
                    player.addPoke(pokeBean);
                    break;
                } else if ("n".equalsIgnoreCase(next)) {
                    break;
                } else {
                    System.out.println("请输入 y/n !");
                }
            }

        }
    }

    private void addGamePlayer() {
        Scanner scanner = new Scanner(System.in);
        System.out.print("你想使用几副扑克牌(1~8):");
        int pokeSum = scanner.nextInt();
        PokeCreate pokeCreate = new PokeCreate(pokeSum);
        PokeCreate.pokeBeanStaticArray = pokeCreate.pokeBeanArray;
        System.out.print("请输入平民数量：");
        int playerSum = scanner.nextInt();
        for (int i = 0; i < playerSum; i++) {
            System.out.print("请输入平民的名字：");
            String name = scanner.next();
            Player playerUser = new Player(name, RoleEnum.CIVILIAN);
            this.players.add(playerUser);
        }
        Player playerPc = new Player("冷酷庄家", RoleEnum.CROUPIER);
        this.players.add(playerPc);
    }


    public void welcome() {
        System.out.println("===================欢迎来到21点游戏===================");
    }

    public void initialize() {
        // 1.洗牌
        this.gamePokeArray = GameUtil.shuffle();
        // 2.庄家发牌给每位玩家发俩张牌，并给自己也发，一明一暗
        sendTwoPokeToPlayer();
    }

    private void sendTwoPokeToPlayer() {
        for (Player player : this.players) {
            PokeBean pokeBean1 = GameUtil.dealCards(gamePokeArray);
            PokeBean pokeBean2 = GameUtil.dealCards(gamePokeArray);
            if (player.getRole().equals(RoleEnum.CROUPIER)) {
                // 庄家的一张牌需要隐藏
                pokeBean1.setShow(false);
            }
            player.addPoke(pokeBean1);
            player.addPoke(pokeBean2);
        }
    }


    private void showAllPlayerPoke() {
        for (Player player : this.players) {
            GameUtil.showPlayerPoke(player);
        }
    }


    private void gameOver() {
        System.out.println("===============Game Over===============");
        showAllPlayerPoke();
        System.out.println("=============Point ranking==============");
        showAllPlayerPokeNumber();
    }

    private void showAllPlayerPokeNumber() {
        List<Player> winner = new ArrayList<>();
        Iterator<Player> iterator = this.players.iterator();
        while (iterator.hasNext()) {
            Player player = iterator.next();
            if (player.getGameJoinStatus().equals(GameJoinEnum.UNDER_WAY)) {
                winner.add(player);
            }
        }
        // 排序胜者
        winner.sort((a, b) -> b.getMaxScore() - a.getMaxScore());
        for (int i = 0; i < winner.size(); i++) {
            Player player = winner.get(i);
            System.out.printf("第%s名 %s 总分 %s ", i + 1, player.getName(), player.getMaxScore());
            GameUtil.showPlayerPoke(player);
        }
    }

    private void showPersonPoke(List<PokeBean> person) {
        for (int i = 0; i < person.size(); i++) {
            PokeBean pokeBean = person.get(i);
            System.out.print(pokeBean.getColor().getDesc() + getPokeNameByNumber(pokeBean.getNumber()) + " ");
        }
        System.out.println("");
    }

    public String getPokeNameByNumber(Integer number) {
        if (number == 1) {
            return "A";
        } else if (number == 11) {
            return "J";
        } else if (number == 12) {
            return "Q";
        } else if (number == 13) {
            return "K";
        }
        return String.valueOf(number);
    }
}
